import { updatePassword, updateUser } from '@/services/UserService';
import { useModel } from '@@/exports';
import ProForm, {
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import { NoticeType } from 'antd/es/message/interface';
import { useState } from 'react';
// import styles from './modal.less';

const closeDynamicView = async () => {
  await window.tm?.ipcRenderer.invoke('closeObsModal');
};
const SettingModal = ({ data }: { data: { data: { type: string } } }) => {
  const { type } = data.data;
  const [userInfo, setUserInfo] = useState(
    JSON.parse(localStorage.getItem('userInfo')!)!,
  );
  const [fileList, setFileList] = useState([
    {
      uid: '-1',
      name: '',
      status: '',
      file: userInfo?.avatar,
      url: userInfo?.avatar,
      thumbUrl: userInfo?.avatar,
    },
  ]);
  const { peerServer } = useModel('global');

  const showMessage = async (data: { type: NoticeType; message: string }) => {
    await window.tm?.ipcRenderer.invoke('sendWindowEvent', {
      name: 'mainWindow',
      event: 'showMessage',
      data: data,
    });
  };
  const success = async (content: string) => {
    await showMessage({
      type: 'success',
      message: content,
    });
  };
  const error = async (content: string) => {
    await showMessage({
      message: content,
      type: 'error',
    });
  };
  const Component = ({ ComponentType }: { ComponentType: string }) => {
    const avatar = () => {
      return (
        <>
          <ProForm<any>
            title="修改头像"
            autoFocusFirstInput
            initialValues={{
              id: userInfo?.id,
              file: fileList,
            }}
            layout={'vertical'}
            onFinish={async (values) => {
              if (values.file && values.file.length > 0) {
                const file = values.file[0];
                if (!file.response) {
                  await error('请上传头像');
                  return;
                }
                const info = {
                  id: userInfo?.id,
                  avatar: decodeURI(file.response.data.fileUrl),
                };
                const { data } = await updateUser(peerServer, info);
                if (data.success) {
                  userInfo.avatar = decodeURI(file.response.data.fileUrl);
                  localStorage.setItem('userInfo', JSON.stringify(userInfo));
                  setUserInfo(userInfo);
                  await success('修改成功');
                  await closeDynamicView();
                } else {
                  await error('修改失败');
                }
              } else {
                await error('请上传头像');
                return;
              }
            }}
          >
            <ProFormText hidden name="id" initialValue={userInfo?.id} />
            <ProFormUploadButton
              label={'头像'}
              action={`${peerServer}/api/file/upload`}
              name="file"
              max={1}
              fieldProps={{
                showUploadList: {
                  showPreviewIcon: false,
                  showRemoveIcon: true,
                },
                headers: {
                  Authorization:
                    'Bearer ' +
                    localStorage.getItem('token')?.replaceAll('"', '') +
                    ' ' +
                    localStorage.getItem('tokenIssueTime'),
                },
                method: 'post',
                beforeUpload: (file: any, fileList: any) => {
                  console.log('file', file);
                  // 后缀获取
                  var suffix = '';
                  // 获取类型结果
                  var result = false;
                  try {
                    if (file) {
                      var fileArr = file.name.split('.');
                      suffix = fileArr[fileArr.length - 1];
                    } else {
                      suffix = '';
                    }
                  } catch (err) {
                    error('文件类型上传错误！');
                    return false;
                  }
                  var imgList = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'];
                  // 进行图片匹配
                  result = imgList.some(function (item) {
                    return item == suffix;
                  });

                  if (!result) {
                    error('文件类型上传错误！');
                  }
                  return result;
                },
                onChange: (info) => {
                  if (info.file.status !== 'uploading') {
                    console.log(info);
                  }
                  if (info.file.status === 'done') {
                    console.log('infoinfoinfoinfo', info);
                    fileList[0].file = info.file.response.data.fileUrl;
                    fileList[0].url = info.file.response.data.fileUrl;
                    fileList[0].thumbUrl = info.file.response.data.fileUrl;
                    setFileList(fileList);
                    success(`${info.file.name} 上传成功`);
                  } else if (info.file.status === 'error') {
                    error(`${info.file.name} 上传失败`);
                  }
                },
              }}
              listType="picture-card"
              className="avatar-uploader"
            ></ProFormUploadButton>
          </ProForm>
        </>
      );
    };
    const nickName = () => {
      return (
        <>
          <ProForm<any>
            title="修改昵称"
            autoFocusFirstInput
            initialValues={{
              id: userInfo?.id,
              userName: userInfo?.userName,
            }}
            onFinish={async (values) => {
              const { data } = await updateUser(peerServer, values);
              if (data.success) {
                await success('修改成功，下次登陆后生效');
                await closeDynamicView();
                return true;
              } else {
                error('修改失败');
                return false;
              }
            }}
          >
            <ProFormText hidden name="id" initialValue={userInfo?.id} />
            <ProFormText
              rules={[{ required: true }]}
              name="userName"
              label="昵称"
              initialValue={userInfo?.userName}
            />
          </ProForm>
        </>
      );
    };
    const password = () => {
      return (
        <>
          <ProForm<any>
            title="修改密码"
            autoFocusFirstInput
            onFinish={async (values) => {
              const { data } = await updatePassword(peerServer, values);
              if (data.success) {
                await success('修改成功，下次登陆后生效');
                await closeDynamicView();
                return true;
              } else {
                error(data.message);
                return false;
              }
            }}
          >
            <ProFormText hidden name="id" initialValue={userInfo?.id} />
            <ProFormText
              rules={[{ required: true }]}
              name="oldPassword"
              label="原密码"
            />
            <ProFormText
              rules={[{ required: true }]}
              name="newPassword"
              label="新密码"
            />
          </ProForm>
        </>
      );
    };
    if (ComponentType === 'avatar') {
      return avatar();
    } else if (ComponentType === 'name') {
      return nickName();
    } else if (ComponentType === 'password') {
      return password();
    } else {
      return <></>;
    }
  };
  return (
    <div>
      <Component ComponentType={type}></Component>
    </div>
  );
};

export default SettingModal;
